// src/utils/initSubscriptions.ts
import axios from 'axios'
import { useStompClient } from '@/composables/useStompClient'

// ✅ 手动解析 JWT（Base64 解码）
export function parseJwt(token: string): any {
  try {
    const base64Url = token.split('.')[1]
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
        .join('')
    )
    return JSON.parse(jsonPayload)
  } catch (e) {
    console.error('❌ 无法解析 JWT', e)
    return null
  }
}

export async function initSubscriptionsFromToken(token: string) {
  const stompClient = useStompClient()
  const payload = parseJwt(token)
  const userId: number = payload?.userId
  if (!userId) throw new Error('token 中缺失 userId')

  // ✅ STOMP 连接
  await stompClient.connect(userId)

  // ✅ 获取好友和群组 ID
  const headers = {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  }

  try {
    // ✅ 好友（私聊）ID（路径固定）
    const friendsRes = await axios.get(`http://localhost:8080/api/friends/getFriend`, {
      headers,
    })
    console.log(friendsRes)

    const friendIds: number[] = friendsRes.data.friends || []
    friendIds.forEach(() => {
      console.log('✅ 私聊路径已统一订阅 /user/queue/messages')
    })

    // ✅ 群组 ID
    const groupRes = await axios.get(`http://localhost:8080/api/chatroom/user/${userId}`, {
      headers,
    })
    console.log(groupRes)
    const groupIds: number[] = groupRes.data.rooms || []
    for (const id of groupIds) {
      await stompClient.subscribeGroup(id)
    }
  } catch (err) {
    console.error('❌ 初始化消息订阅失败', err)
  }
}
